package com.fenrirtec.aepp.common.service.impl;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.fenrirtec.aepp.common.dao.CodeNameDao;
import com.fenrirtec.aepp.common.dao.impl.CodeNameDao_JDBCImpl;
import com.fenrirtec.aepp.common.dto.CodeNameDto;
import com.fenrirtec.aepp.common.model.CodeName;
import com.fenrirtec.aepp.common.service.CodeNameService;
import com.fenrirtec.core.database.DatabaseSessionManager;
import com.fenrirtec.core.exception.DatabaseException;
import com.fenrirtec.core.exception.UnexpectedException;
import com.fenrirtec.core.utils.BeanCopierUtils;

public class CodeNameServiceImpl implements CodeNameService {

	private static final Logger logger = LoggerFactory.getLogger(CodeNameServiceImpl.class);

	@Override
	public List<CodeNameDto> findByTypeId(String typeId) {
		if (logger.isInfoEnabled()) {
			logger.info("[CodeNameServiceImpl#findByTypeId] start.");
		}
		
		DatabaseSessionManager sessionManager = DatabaseSessionManager.getInstance();
		sessionManager.open();
		Connection connection = sessionManager.getSession();

		List<CodeName> codeNames = null;
		
		try {
			connection.setAutoCommit(false);
			CodeNameDao codeNameDao = new CodeNameDao_JDBCImpl();
			codeNames = codeNameDao.findByTypeId(typeId);
			connection.commit();
		} catch (DatabaseException e) {
			// expected
			if (logger.isErrorEnabled()) {
				logger.error("[CodeNameServiceImpl#findByTypeId] database error occurred.", e);
			}
			try {
				connection.rollback();
			} catch (SQLException e1) {
			}
			throw e;
		} catch (Exception e) {
			// unexpected
			if (logger.isErrorEnabled()) {
				logger.error("[CodeNameServiceImpl#findByTypeId] unexpected error occurred.", e);
			}
			try {
				connection.rollback();
			} catch (SQLException e1) {
			}
			throw new UnexpectedException("unexpected error.", e);
		} finally {
			if (logger.isInfoEnabled()) {
				logger.info("[CodeNameServiceImpl#findByTypeId] finish.");
			}
			sessionManager.close();
		}

		List<CodeNameDto> codeNameDtos = new ArrayList<CodeNameDto>();
		if (codeNames != null && codeNames.size() > 0) {
			for (CodeName codeName : codeNames) {
				CodeNameDto codeNameDto = new CodeNameDto();
				BeanCopierUtils.copyProperties(codeName, codeNameDto);
				codeNameDtos.add(codeNameDto);
			}
		}
		return codeNameDtos;
	}
}
